<template>
  <!-- 模板部分保持不变，无需修改 -->
  <div class="carbon-platform d-flex flex-column min-vh-100">
    <!-- 加载动画 -->
    <div class="preloader-wrapper" v-if="isLoading">
      <div class="preloader"></div>
    </div>

    <!-- 导航栏 -->
    <nav class="navbar sticky-top bg-white shadow-sm py-3">
      <div class="container">
        <div class="d-flex justify-content-between align-items-center w-100">
          <!-- 网站标志 -->
          <div class="navbar-logo">
            <span class="logo-icon">🌱</span>
            <span class="logo-text">绿碳平台</span>
          </div>

          <!-- 中间导航链接 - 桌面版 -->
          <ul class="navbar-nav list-unstyled d-flex flex-row gap-3 gap-lg-5 justify-content-center flex-wrap align-items-center mb-0 fw-bold flex-grow-1 mx-4">
            <li class="nav-item">
              <a href="/index" class="nav-link text-dark hover:text-primary transition-colors">首页</a>
            </li>
            <li class="nav-item">
              <a href="/shop" class="nav-link text-dark hover:text-primary transition-colors">碳积分市场</a>
            </li>
            <li class="nav-item">
              <a href="/blog" class="nav-link text-dark hover:text-primary transition-colors">博客</a>
            </li>
            <li class="nav-item">
              <a href="/contact" class="nav-link text-dark hover:text-primary transition-colors">联系我们</a>
            </li>
            <li class="nav-item">
              <a href="/about" class="nav-link text-dark hover:text-primary transition-colors">关于我们</a>
            </li>
            <li class="nav-item">
              <a href="/order" class="nav-link text-dark hover:text-primary transition-colors">我的订单</a>
            </li>
          </ul>

          <!-- 右侧功能区 -->
          <div class="d-flex align-items-center gap-4 gap-lg-5">
            <!-- 搜索按钮 -->
            <button class="btn p-2 text-dark hover:text-primary transition-colors" aria-label="搜索">
              <span class="fs-5">🔍</span>
            </button>

            <!-- 购物车 -->
            <a href="/cart" class="btn p-2 text-dark hover:text-primary transition-colors position-relative" aria-label="购物车">
              <span class="fs-5">🛒</span>
            </a>

            <!-- 用户菜单 -->
            <div class="dropdown">
              <button class="btn p-2 text-dark hover:text-primary transition-colors" type="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="用户菜单">
                <span class="fs-5">👤</span>
              </button>
              <ul class="dropdown-menu dropdown-menu-end">
                <li><a class="dropdown-item" href="/login">登录</a></li>
                <li><a class="dropdown-item" href="/register">注册</a></li>
                <li><a class="dropdown-item" href="/account">企业账户</a></li>
              </ul>
            </div>

            <!-- 移动端菜单按钮 -->
            <button class="btn d-lg-none p-2 text-dark" type="button" data-bs-toggle="offcanvas" data-bs-target="#mobileMenu" aria-label="菜单">
              <span class="fs-5">☰</span>
            </button>
          </div>
        </div>
      </div>
    </nav>

    <!-- 主内容区域 - 左侧图片+右侧表单布局 -->
    <main class="register-page flex-grow-1 bg-green-carbon">
      <div class="container-lg h-100">
        <!-- 外层容器：控制整体宽度和居中 -->
        <div class="row justify-content-center align-items-center h-100">
          <div class="col-12 col-xl-10 my-8">
            <!-- 核心布局：左侧图片 + 右侧表单 -->
            <div class="row g-0 g-lg-8 align-items-center h-100">
              <!-- 左侧图片区域（仅桌面版显示） -->
              <div class="col-lg-6 d-none d-lg-flex h-100">
                <div class="register-image-wrapper rounded-lg overflow-hidden shadow-lg h-100 w-100">
                  <img
                      src="/images/img-login.jpg"
                      alt="绿碳平台登录页面"
                      class="register-image w-100 h-100 object-cover"
                  >
                </div>
              </div>

              <!-- 右侧表单区域 -->
              <div class="col-lg-6 h-100">
                <div class="card register-card shadow-lg border-0">
                  <div class="card-body p-6 p-lg-8 d-flex flex-column">
                    <!-- 表单标题 -->
                    <div class="text-center mb-6">
                      <h2 class="register-title">用户登录</h2>
                      <p class="text-muted">登录您的账户，开启绿碳之旅</p>
                    </div>

                    <!-- 显示路由携带的提示信息（如“请先登录以访问该页面”） -->
                    <div v-if="loginMessage" class="alert alert-info mb-4 text-center" role="alert">
                      {{ loginMessage }}
                    </div>

                    <!-- 登录表单 -->
                    <form @submit.prevent="handleLogin" class="register-form flex-grow-1">
                      <!-- 登录类型选择 -->
                      <div class="mb-4">
                        <div class="btn-group w-100" role="group">
                          <button
                              type="button"
                              class="btn"
                              :class="loginType === 'company' ? 'btn-primary' : 'btn-outline-primary'"
                              @click="loginType = 'company'"
                          >
                            企业登录
                          </button>
                          <button
                              type="button"
                              class="btn"
                              :class="loginType === 'admin' ? 'btn-primary' : 'btn-outline-primary'"
                              @click="loginType = 'admin'"
                          >
                            管理员登录
                          </button>
                        </div>
                      </div>

                      <!-- 企业登录表单 -->
                      <div v-if="loginType === 'company'">
                        <!-- 企业统一社会信用代码 -->
                        <div class="mb-4">
                          <label class="form-label required">统一社会信用代码</label>
                          <input type="text" class="form-control"
                                 v-model="companyLoginForm.creditCode"
                                 :class="{ 'is-invalid': errors.creditCode }"
                                 placeholder="请输入18位统一社会信用代码" required>
                          <div class="invalid-feedback">{{ errors.creditCode }}</div>
                        </div>

                        <!-- 密码 -->
                        <div class="mb-4">
                          <label class="form-label required">密码</label>
                          <input type="password" class="form-control"
                                 v-model="companyLoginForm.password"
                                 :class="{ 'is-invalid': errors.password }"
                                 placeholder="请输入密码" required>
                          <div class="invalid-feedback">{{ errors.password }}</div>
                        </div>
                      </div>

                      <!-- 管理员登录表单 -->
                      <div v-if="loginType === 'admin'">
                        <!-- 管理员账号 -->
                        <div class="mb-4">
                          <label class="form-label required">管理员账号</label>
                          <input type="text" class="form-control"
                                 v-model="adminLoginForm.username"
                                 :class="{ 'is-invalid': errors.username }"
                                 placeholder="请输入管理员账号" required>
                          <div class="invalid-feedback">{{ errors.username }}</div>
                        </div>

                        <!-- 密码 -->
                        <div class="mb-4">
                          <label class="form-label required">密码</label>
                          <input type="password" class="form-control"
                                 v-model="adminLoginForm.password"
                                 :class="{ 'is-invalid': errors.password }"
                                 placeholder="请输入密码" required>
                          <div class="invalid-feedback">{{ errors.password }}</div>
                        </div>
                      </div>

                      <!-- 记住我 -->
                      <div class="mb-4 form-check">
                        <input type="checkbox" class="form-check-input" id="rememberMe" v-model="rememberMe">
                        <label class="form-check-label" for="rememberMe">记住我</label>
                      </div>

                      <!-- 提交按钮 -->
                      <div class="d-grid gap-3 mt-4">
                        <button type="submit" class="btn btn-primary btn-lg" :disabled="isSubmitting">
                          {{ isSubmitting ? '登录中...' : '立即登录' }}
                        </button>
                        <p class="text-center text-muted">
                          还没有账号？<a href="/register" class="text-primary">立即注册</a>
                        </p>
                      </div>
                    </form>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 页脚 - 固定在页面底部 -->
    <footer class="main-footer mt-auto">
      <div class="container">
        <div class="footer-bottom">
          <p class="copyright">© 2025 绿碳平台 版权所有 | 京ICP备12345678号</p>
        </div>
      </div>
    </footer>
  </div>
</template>

<script>
import { userApi } from '../api/index.js'

export default {
  name: 'Login',
  data() {
  return {
  isLoading: false,
  isSubmitting: false,
  loginType: 'company', // 'company' 或 'admin'
  rememberMe: false,
  companyLoginForm: {
  creditCode: '',
  password: ''
},
  adminLoginForm: {
  username: '',
  password: ''
},
  errors: {},
  loginMessage: '', // 用于显示路由携带的提示信息
  redirectPath: '' // 添加redirectPath变量
};
},
  mounted() {
  // 页面加载时，读取路由query中的message和redirect参数
  const { message, redirect } = this.$route.query;
  // 显示提示信息
  if (message) this.loginMessage = message;
  // 保存redirect参数到实例，供登录成功后使用
  this.redirectPath = redirect || '/admin/dashboard'; // 默认跳转仪表盘
},
  methods: {
  validateForm() {
  // 保持不变
  const errors = {};

  if (this.loginType === 'company') {
  // 企业登录验证
  if (!this.companyLoginForm.creditCode) {
  errors.creditCode = '请输入统一社会信用代码';
} else if (!/^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/.test(this.companyLoginForm.creditCode)) {
  errors.creditCode = '请输入有效的18位统一社会信用代码';
}

  if (!this.companyLoginForm.password) {
  errors.password = '请输入密码';
}
} else {
  // 管理员登录验证
  if (!this.adminLoginForm.username) {
  errors.username = '请输入管理员账号';
}

  if (!this.adminLoginForm.password) {
  errors.password = '请输入密码';
}
}

  this.errors = errors;
  return Object.keys(errors).length === 0;
},
  async handleLogin() {
    if (!this.validateForm()) return;

    this.isSubmitting = true;
    try {
      if (this.loginType === 'company') {
        // 企业登录逻辑 - 使用统一社会信用代码作为用户名
        const response = await userApi.login(this.companyLoginForm.creditCode, this.companyLoginForm.password);
        
        if (response.data && response.data.code === '1') {
          // 登录成功，保存企业信息到本地存储
          const userData = response.data.obj;
          localStorage.setItem('currentCompany', JSON.stringify(userData));
          localStorage.setItem('currentUser', JSON.stringify(userData));
          
          // 跳转到企业账户页
          this.$router.push('/account');
        } else {
          this.errors.password = response.data?.message || '统一社会信用代码或密码错误';
        }
      } else {
        // 管理员登录逻辑
        const response = await userApi.login(this.adminLoginForm.username, this.adminLoginForm.password);
        
        if (response.data && response.data.code === '1') {
          // 登录成功，保存管理员信息
          const userData = response.data.obj;
          localStorage.setItem('currentUser', JSON.stringify(userData));
          
          // 根据用户角色跳转到对应页面
          if (userData.role === 'ADMIN') {
            this.$router.push('/admin/dashboard');
          } else {
            this.$router.push('/account');
          }
        } else {
          this.errors.password = response.data?.message || '管理员账号或密码错误';
        }
      }
    } catch (error) {
      console.error('登录失败:', error);
      if (error.response && error.response.data) {
        this.errors.password = error.response.data.message || '登录失败，请检查网络连接';
      } else {
        this.errors.password = '登录失败，请稍后重试';
      }
    } finally {
      this.isSubmitting = false;
    }
  }
}
};
</script>

<style scoped>
.navbar-logo {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 1.5rem;
  font-weight: bold;
  color: #2e7d32; /* 绿色主色调 */
}

.register-page {
  padding: 2rem 0;
  display: flex;
  align-items: center;
}

.register-card {
  border-radius: 12px;
  background-color: white;
  max-width: 500px;
  width: 100%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
}

.register-title {
  font-size: 1.8rem;
  font-weight: 700;
  color: #2e7d32;
}

.form-label.required::after {
  content: '*';
  color: #dc3545;
  margin-left: 4px;
}

.form-control, .form-select {
  border-radius: 8px;
  padding: 0.75rem;
  border: 1px solid #ced4da;
  transition: all 0.3s ease;
}

.form-control:focus, .form-select:focus {
  border-color: #4caf50;
  box-shadow: 0 0 0 0.25rem rgba(76, 175, 80, 0.25);
  outline: none;
}

.btn-primary {
  background-color: #2e7d32;
  border-color: #2e7d32;
  padding: 0.75rem;
  font-weight: 600;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.btn-primary:hover, .btn-primary:focus {
  background-color: #1b5e20;
  border-color: #1b5e20;
  transform: translateY(-2px);
}

.btn-outline-primary {
  color: #2e7d32;
  border-color: #2e7d32;
}

.btn-outline-primary:hover, .btn-outline-primary:focus {
  background-color: #2e7d32;
  border-color: #2e7d32;
  color: white;
}

.register-image-wrapper {
  border-radius: 12px;
  height: 100%;
  min-height: 500px;
}

.main-footer {
  background-color: #2E7D32;
  padding: 2rem 0;
  width: 100%;
}

.copyright {
  text-align: center;
  margin: 0;
  color: #fff;
}

/* 提示信息样式 */
.alert-info {
  background-color: #d1ecf1;
  border-color: #bee5eb;
  color: #0c5460;
  padding: 0.75rem 1.25rem;
  border-radius: 0.5rem;
}

@media (max-width: 991.98px) {
  .register-image-wrapper {
    display: none;
  }

  .register-card {
    margin-top: 2rem;
    margin-bottom: 2rem;
  }

  .register-page {
    padding: 1rem 0;
  }
}

.transition-colors {
  transition: color 0.3s ease;
}

.preloader-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.preloader {
  width: 50px;
  height: 50px;
  border: 5px solid #f3f3f3;
  border-top: 5px solid #2e7d32;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>